package br.com.beiramar.action.TesteGeraPdf;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Map;

import javax.faces.context.FacesContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import net.sf.jasperreports.engine.JREmptyDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import br.com.beiramar.entity.pessoa.testeDaniloPdf.Teste;

public class GerarPdfTeste {
	
	public GerarPdfTeste(String reportUrlReal, Map<String, Object> parametros){
		Teste teste = (Teste) parametros.get("TESTE");
		FacesContext facesContext = FacesContext.getCurrentInstance();
		HttpServletResponse response = (HttpServletResponse) facesContext
		.getExternalContext().getResponse();
		
		JasperPrint jasperPrint;
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		try {
			jasperPrint = JasperFillManager.fillReport(reportUrlReal, parametros, new JREmptyDataSource());
			
			JasperExportManager.exportReportToPdfStream(jasperPrint, output);
		} catch (JRException e) {
			e.printStackTrace();
		}

		// Escrever o byteArray no response
		
		response.setContentType("application/pdf");
		response.addHeader("Content-Disposition",
				"attachment;filename=" + teste.getNome().replaceAll(" ", "_")+ "_"+ teste.getCpf() + ".pdf");
		response.setContentLength(output.toByteArray().length);
		ServletOutputStream servletOutputStream;
		try {
			servletOutputStream = response
					.getOutputStream();
			servletOutputStream.write(output.toByteArray(), 0, output
					.toByteArray().length);
			servletOutputStream.flush();
			servletOutputStream.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		FacesContext.getCurrentInstance().responseComplete();
		
	}
	
	

}
